package com.ellen.mac.chatdemo.view;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.AnimationDrawable;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.View;
import android.widget.SeekBar;
import android.widget.TextView;

import com.ellen.mac.chatdemo.R;
import com.ellen.mac.chatdemo.utils.AudioHelper;
import com.ellen.mac.chatdemo.utils.LogUtils;

/**
 * Created by lzw on 14-9-22.
 * 语音播放按钮
 */
@SuppressLint("AppCompatCustomView")
public class PlayButton extends TextView implements View.OnClickListener, SeekBar.OnSeekBarChangeListener {
    private String path;
    private boolean leftSide;
    private AnimationDrawable anim;
    protected SeekBar seekbar;
    private Handler handler = new Handler();
    private Runnable changeProgress = new Runnable() {
        @Override
        public void run() {
            if (handler != null && isPlaying()) {
                int progress = AudioHelper.getInstance().getMadiaPlayer().getCurrentPosition();
                if(seekbar!=null){
                    seekbar.setProgress(progress / 1000);
                }
            }
            handler.postDelayed(this, 1000);
        }
    };

    public PlayButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        leftSide = getLeftFromAttrs(context, attrs);
        setLeftSide(leftSide);
        setOnClickListener(this);
    }

    /**
     * 设置语音按钮的方向
     * 因为聊天中左右 item 都可能有语音
     *
     * @param leftSide
     */
    public void setLeftSide(boolean leftSide) {
        this.leftSide = leftSide;
        stopRecordAnimation();
    }

    private boolean getLeftFromAttrs(Context context, AttributeSet attrs) {
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.chat_play_button);
        boolean left = true;
        for (int i = 0; i < typedArray.getIndexCount(); i++) {
            int attr = typedArray.getIndex(i);
            if (attr == R.styleable.chat_play_button_left) {
                left = typedArray.getBoolean(attr, true);
            }
        }
        return left;
    }

    /**
     * 设置语音文件位置
     *
     * @param path
     */
    public void setPath(String path) {
        this.path = path;
        stopRecordAnimation();
        if (isPlaying()) {
            AudioHelper.getInstance().addFinishCallback(new AudioHelper.AudioFinishCallback() {
                @Override
                public void onFinish() {
                    stopRecordAnimation();
                }
            });
            startRecordAnimation();
        }
    }

    public void initSeekBar(SeekBar seekbar, Context context) {
        this.seekbar = seekbar;
        seekbar.setOnSeekBarChangeListener(this);
    }

    private boolean isPlaying() {
        return AudioHelper.getInstance().isPlaying() == true &&
                AudioHelper.getInstance().getAudioPath().equals(path);
    }

    @Override
    public void onClick(View v) {
        if (AudioHelper.getInstance().isPlaying() == true && AudioHelper.getInstance().getAudioPath().equals(path)) {
            stop();
        } else {
            start();
        }
    }

    private void start() {
        AudioHelper.getInstance().playAudio(path);
        handler.post(changeProgress);
        AudioHelper.getInstance().addFinishCallback(new AudioHelper.AudioFinishCallback() {
            @Override
            public void onFinish() {
                stopRecordAnimation();
            }
        });
        startRecordAnimation();
    }

    private void stop() {
        AudioHelper.getInstance().pausePlayer();
        handler.removeCallbacks(changeProgress);
        stopRecordAnimation();
    }

    /**
     * 开始播放语音动画
     */
    private void startRecordAnimation() {
        setCompoundDrawablesWithIntrinsicBounds(leftSide ? R.drawable.chat_anim_voice_left : 0,
                0, !leftSide ? R.drawable.chat_anim_voice_right : 0, 0);
        anim = (AnimationDrawable) getCompoundDrawables()[leftSide ? 0 : 2];
        anim.start();
    }

    /**
     * 停止播放语音动画
     */
    private void stopRecordAnimation() {
        setCompoundDrawablesWithIntrinsicBounds(leftSide ? R.mipmap.chat_voice_right3 : 0,
                0, !leftSide ? R.mipmap.chat_voice_left3 : 0, 0);
        if (anim != null) {
            anim.stop();
        }
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        if (fromUser) {
            if (!isPlaying()) {
                start();
            }
            AudioHelper.getInstance().getMadiaPlayer().seekTo(progress * 1000);
            LogUtils.i(AudioHelper.getInstance().getMadiaPlayer().getCurrentPosition() + "--0--");

        }
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {

    }
}
